//
//  KLImplementCommondsTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/6/11.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLImplementCommondsTableViewController.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "KLHttpAPI.h"
#import "Masonry.h"
#import "UIAlertView+Blocks.h"

@interface KLImplementCommondsTableViewController ()
@property (nonatomic,strong) NSArray *commondLisrArr;
@end

@implementation KLImplementCommondsTableViewController

-(void)viewWillAppear:(BOOL)animated{
    [self refreshCommand];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"委托命令";
    //初始化导航栏
    [self naveSet];
    self.tableView.tableFooterView = [[UIView alloc]init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshCommand) name:@"refreshCommand" object:nil];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.commondLisrArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.commondLisrArr[indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commondList"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"commondList"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    //锁名
    UILabel *lockName = [[UILabel alloc]init];
    lockName.text = [NSString stringWithFormat:@"锁别名:%@",[dic objectForKey:@"name"]];
    lockName.textAlignment = NSTextAlignmentLeft;
    lockName.font = [UIFont systemFontOfSize:15];
    [cell.contentView addSubview:lockName];
    [lockName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(6);
        make.left.mas_equalTo(5);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(25);
    }];
    
    //指令名
    UILabel *commondName = [[UILabel alloc]init];
    NSString *type = [dic objectForKey:@"type"];
    if(type.integerValue == 0){
        commondName.text = @"指令名:校时";
    }else if (type.integerValue == 1){
        commondName.text = @"指令名:设置黑名单";
    }else if (type.integerValue == 2){
        commondName.text = @"指令名:取消黑名单";
    }
    commondName.textAlignment = NSTextAlignmentRight;
    commondName.font = [UIFont systemFontOfSize:15];
    commondName.textColor = RGB_UI_COLOR(102, 153, 255);
    [cell.contentView addSubview:commondName];
    [commondName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(6);
        make.right.mas_equalTo(-30);
        make.width.mas_equalTo(130);
        make.height.mas_equalTo(25);
    }];
    
    //地址
    UILabel *address = [[UILabel alloc]init];
    address.text = [NSString stringWithFormat:@"地址:%@",[dic objectForKey:@"address"]];
    address.textAlignment = NSTextAlignmentLeft;
    address.font = [UIFont systemFontOfSize:13];
    address.alpha = 0.5;
    [cell.contentView addSubview:address];
    [address mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell.contentView);
        make.right.mas_equalTo(5);
        make.width.mas_equalTo(UI_View_Width);
        make.height.mas_equalTo(20);
    }];
    
    //来自用户手机号
    UILabel *receivePhone = [[UILabel alloc]init];
    receivePhone.text = [NSString stringWithFormat:@"来自用户:%@ （%@）",[dic objectForKey:@"mobile"],[dic objectForKey:@"username"]];
    receivePhone.textAlignment = NSTextAlignmentLeft;
    receivePhone.font = [UIFont systemFontOfSize:13];
    receivePhone.alpha = 0.5;
    [cell.contentView addSubview:receivePhone];
    [receivePhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-6);
        make.right.mas_equalTo(5);
        make.width.mas_equalTo(UI_View_Width);
        make.height.mas_equalTo(20);
    }];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *commondInfo = self.commondLisrArr[indexPath.section];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请离锁30cm内点击确定" message:nil cancelButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
        if([[commondInfo objectForKey:@"type"] isEqualToString:@"0"]){
            //发委托校时的通知
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSString stringWithFormat:@"1"] forKey:@"commondType"];
            [dic setObject:commondInfo forKey:@"currentLockInfo"];
            [dic setObject:self.view forKey:@"lockDetailView"];
            [dic setObject:[commondInfo objectForKey:@"id"] forKey:@"command_id"];
            //给主界面发通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"checkOutTime" object:nil userInfo:dic];
        }else if([[commondInfo objectForKey:@"type"] isEqualToString:@"1"]){
            //发委托设置黑名单的通知
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSString stringWithFormat:@"2"] forKey:@"commondType"];
            [dic setObject:commondInfo forKey:@"currentLockInfo"];
            [dic setObject:self.view forKey:@"lockDetailView"];
            [dic setObject:[commondInfo objectForKey:@"command"] forKey:@"blackPhone"];
            [dic setObject:[commondInfo objectForKey:@"id"] forKey:@"command_id"];
            //给主界面发通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"settingBlackList" object:nil userInfo:dic];
        }else if([[commondInfo objectForKey:@"type"] isEqualToString:@"2"]){
            //发委托取消黑名单的通知
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSString stringWithFormat:@"3"] forKey:@"commondType"];
            [dic setObject:commondInfo forKey:@"currentLockInfo"];
            [dic setObject:self.view forKey:@"lockDetailView"];
            [dic setObject:[commondInfo objectForKey:@"command"] forKey:@"blackPhone"];
            [dic setObject:[commondInfo objectForKey:@"id"] forKey:@"command_id"];
            //给主界面发通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelBlackList" object:nil userInfo:dic];
        }
    }], nil];
    [alert show];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSDictionary *commandDic = self.commondLisrArr[section];
    UIView *sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 25)];
    UILabel *timeLabel = [[UILabel alloc]init];
    timeLabel.font = [UIFont systemFontOfSize:14 weight:0.5];
    timeLabel.textColor = RGB_UI_COLOR(255, 130, 71);
    NSString *beginTime = [commandDic objectForKey:@"begintime"];
    NSString *endTime = [commandDic objectForKey:@"endtime"];
    beginTime = [beginTime substringToIndex:beginTime.length-3];
    endTime = [endTime substringToIndex:endTime.length-3];
    timeLabel.text = [NSString stringWithFormat:@"时效:%@至%@",beginTime,endTime];
    [sectionView addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.centerY.equalTo(sectionView);
    }];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 24, UI_View_Width, 0.3)];
    line.backgroundColor = [UIColor lightGrayColor];
    [sectionView addSubview:line];
    
    return sectionView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25.f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75;
}

#pragma mark - 初始化导航栏
-(void)naveSet{
    self.navigationController.navigationBarHidden = NO;
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)refreshCommand{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI getCommondListWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] completionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"命令列表:%@",operation.responseJSON);
        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        if(isSuccess.integerValue == 1 && ![[operation.responseJSON objectForKey:@"infor"] isKindOfClass:[NSNull class]]){
            self.commondLisrArr = [operation.responseJSON objectForKey:@"infor"];
            if(self.commondLisrArr.count == 0){
                [KLHelp setNoDateImageWithView:self.view type:0];
            }
            [self.tableView reloadData];
        }else{
            [JRToast showWithText:[operation.responseJSON objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHelp setNoDateImageWithView:self.view type:1];
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
